<template>
  <div :class="[isActivateCompany ? '' : 'layout-main']" class="no-side-menu">
    <div class="authentication" ref="authentication">
      <template v-if="finish">
        <div class="finish">
          <a-result title="您已通过认证" status="success"> </a-result>
        </div>
      </template>
      <template v-else>
        <div class="unfinished">
          <c-steps v-model="current" :steps="steps" />
          <userForm
            v-if="current === 0"
            :userAuthData="userAuthData"
            @success="userSubmitSuccess"
          />
          <companyForm
            v-else-if="current === 1"
            @noEnter="companynoEnter"
            @success="companySubmitSuccess"
          />
          <corporateForm
            v-else-if="current === 2 && enterpriseNoEnter"
            :userAuthData="userAuthData"
            @success="corporateSubmitSuccess"
          />
          <backfillForm
            v-else-if="current === 3 && enterpriseNoEnter"
            :userAuthData="userAuthData"
            @success="backfillFormSubmitSuccess"
            @backTocCompany="backTocCompany"
          />
          <div
            class="auditor"
            v-if="
              (!enterpriseNoEnter && current === 3) ||
                (enterpriseNoEnter && current === 5)
            "
          >
            <a-result
              title="审核中"
              sub-title="您提交的资料正在审核中，请耐心等待"
            >
              <template #extra>
                <div class="tc">
                  <span class="bold fs-16 danger">{{ timeoutSec }}</span>
                  秒后返回切换公司列表
                </div>
              </template>
            </a-result>
          </div>
        </div>
      </template>
    </div>
    <!-- <template v-if="authenticationContinue"> -->
    <c-faceContainer
      v-model="authenticationContinueFaceVisible"
      :userData="{
        name: authenticationContinueData.realName,
        id: authenticationContinueData.residentId
      }"
    >
      <template v-slot:title>
        <a-alert
          show-icon
          type="warning"
          message="由于之前未完成身份认证流程，强制退出页面，需重新刷脸核身认证，证明是用户本人操作而非其他人操作。"
          v-if="authType === 'authenticationContinue'"
        ></a-alert>
        <a-alert
          show-icon
          type="warning"
          message="请先完成刷脸核身认证后再进行操作"
          v-if="authType === 'addCompany' || authType === 'addCompany-backfill'"
        ></a-alert>
      </template>
    </c-faceContainer>
    <!-- </template> -->
    <!-- <div
      class="modal"
      v-if="authenticationContinue && authenticationContinueFaceVisible"
    >
      <div class="face">
        <a-alert
          show-icon
          type="warning"
          message="由于之前未完成身份认证流程，强制退出页面，需重新刷脸核身认证，证明是用户本人操作而非其他人操作。"
          v-if="authType === 'authenticationContinue'"
        ></a-alert>
        <a-alert
          show-icon
          type="warning"
          message="请先完成刷脸核身认证后再进行操作"
          v-if="authType === 'addCompany' || authType === 'addCompany-backfill'"
        ></a-alert>
        <div class="qrcode">
          <a-spin :spinning="authenticationContinueFaceLoading">
            <cQrcode :url="authenticationContinueFaceUrl" />
          </a-spin>
        </div>
        <div class="tip tc">若已完成刷脸，请点击下方按钮</div>
        <c-button type="danger" :loading="faceFinishLoading" @click="faceFinish"
          >我已刷脸</c-button
        >
        <div class="authenticationContinueFaceType">
          <a-radio-group
            v-model="authenticationContinueFaceType"
            @change="changeAuthenticationContinueFaceType"
          >
            <a-radio :value="2">
              支付宝刷脸认证
            </a-radio>
            <a-radio :value="1">
              微信刷脸认证
            </a-radio>
          </a-radio-group>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script>
import cSteps from "@/components/steps";
// import cQrcode from "@/components/qrcode";
import userForm from "./components/user";
import companyForm from "./components/company";
import corporateForm from "./components/corporate";
import backfillForm from "./components/backfill";
import faceContainer from "@/components-business/face/face-container";
// import { mapState } from "vuex";
import { getUserAuthstate } from "@/api/certify";
import { isLogin } from "@/util/auth";
import auth from "@/dict/auth";

// 动态steps
const steps = [
  {
    title: "个人实名认证"
  },
  {
    title: "企业认证"
  },
  {
    title: "完成"
  }
];
const stepsEnter = [
  {
    title: "个人实名认证"
  },
  {
    title: "企业认证"
  },
  {
    title: "对公账户认证"
  },
  {
    title: "回填金额"
  },
  {
    title: "完成"
  }
];

export default {
  components: {
    cSteps,
    // cQrcode,
    userForm,
    companyForm,
    corporateForm,
    backfillForm,
    cFaceContainer: faceContainer
  },
  data() {
    return {
      authType: undefined, // 认证类型
      // authState: undefined,
      current: undefined,
      enterpriseNoEnter: false,
      steps: [],
      finish: false,
      userAuthData: undefined,
      authenticationContinue: false, // 是否继续认证
      authenticationContinueData: {}, // 继续认证获取到的个人认证信息
      authenticationContinueFaceVisible: false, // 继续认证弹窗显隐
      authenticationContinueFaceType: 2, // 继续认证选择的刷脸方式
      authenticationContinueFaceUrl: undefined, // 继续认证刷脸二维码链接
      authenticationContinueFaceFlowid: undefined, // 继续认证刷脸flowid
      authenticationContinueFaceLoading: false, // 继续认证二维码loading
      faceFinishLoading: false, // 是否正在查询刷脸结果
      timeoutSec: 3 // 审核中设置3秒后返回切换公司列表
    };
  },
  computed: {
    // ...mapState(["user"]),
    // msg() {
    //   return this.$store.state.socket && this.$store.state.socket.msgRealnameFace;
    // },
    // 是否激活企业
    isActivateCompany() {
      return this.$route.name === "activateCompany" ? true : false;
    }
  },
  // watch: {
  //   msg(newVal) {
  //     if (newVal.code === 0) {
  //       this.authenticationContinueFaceVisible = false;
  //     }
  //   }
  // },
  methods: {
    // // 已完成刷脸
    // faceFinish() {
    //   this.faceFinishLoading = true;
    //   esignauthdetail({
    //     flowId: this.authenticationContinueFaceFlowid
    //   })
    //     .then(res => {
    //       if (res.status === "SUCCESS") {
    //         this.authenticationContinueFaceVisible = false;
    //       } else if (res.status === "FAIL") {
    //         this.$message.error("刷脸失败，请重试");
    //       } else {
    //         this.$message.warning("请先进行刷脸");
    //       }
    //     })
    //     .finally(() => {
    //       this.faceFinishLoading = false;
    //     });
    // },
    // // 继续认证，切换刷脸方式
    // changeAuthenticationContinueFaceType() {
    //   this.getQrcode(this.authenticationContinueData);
    // },
    // 倒计时返回切换公司列表
    backChangeCompanyList() {
      // 3秒后返回切换公司列表
      let interval = setInterval(() => {
        this.timeoutSec--;
        if (this.timeoutSec <= 0) {
          // 清除定时器
          clearInterval(interval);
          this.$router.push({ name: "changeCompany" });
        }
      }, 1000);
    },
    // 返回首页
    goHome() {
      this.$router.push({ name: "home" });
    },
    // 返回企业认证
    backTocCompany() {
      this.current = 1;
      this.steps = steps;
      this.enterpriseNoEnter = false;
      this.$storage.s_remove("userAuthData");
    },
    // 回填金额成功
    backfillFormSubmitSuccess() {
      this.current = 5;
      this.backChangeCompanyList();
    },
    // 对公账户认证成功
    corporateSubmitSuccess() {
      this.current = 3;
    },
    // 企业认证提交成功
    companySubmitSuccess(res) {
      // 判断是否是新企业认证，已入驻的企业认证res为undefined
      if (res) {
        this.userAuthData = {
          flowId: res.flowId,
          companyName: res.companyName
        };
        this.current = 2;
      } else {
        this.current = 3;
        // 3秒后返回切换公司列表
        this.backChangeCompanyList();
      }
    },
    // 个人实名认证成功
    userSubmitSuccess() {
      this.current = 1;
    },
    // 企业未入驻
    companynoEnter() {
      this.steps = stepsEnter;
      this.enterpriseNoEnter = true;
    },
    // getQrcode(data) {
    //   this.authenticationContinueFaceLoading = true;
    //   // 获取支付宝/微信刷脸二维码
    //   userfaceauth({
    //     userFullName: data.realName,
    //     residentId: data.residentId,
    //     faceAuthMode: this.authenticationContinueFaceType,
    //     callbackUrl: "https://h5.manytrader.net/facePay"
    //   })
    //     .then(res => {
    //       this.authenticationContinueFaceUrl = res.authUrl;
    //       this.authenticationContinueFaceFlowid = res.flowId;
    //     })
    //     .finally(() => {
    //       this.authenticationContinueFaceLoading = false;
    //     });
    // },
    init() {
      // 重新认证
      if (this.$route.query.name) {
        getUserAuthstate().then(res => {
          this.authenticationContinueData = res;
          this.authType = "authenticationContinue";
          this.authenticationContinue = true;
          this.authenticationContinueFaceVisible = true;
          this.current = 1;
          this.steps = steps;
        });
      } else if (this.$storage.s_get("addCompany")) {
        this.authType = "addCompany";
        // 添加公司抬头
        getUserAuthstate().then(res => {
          this.authenticationContinueData = res;
          // this.getQrcode(this.authenticationContinueData);
          this.authenticationContinue = true;
          this.authenticationContinueFaceVisible = true;
          this.current = 1;
          this.steps = steps;
        });
      } else if (this.$storage.s_get("addCompany-backfill")) {
        this.authType = "addCompany-backfill";
        getUserAuthstate().then(res => {
          this.authenticationContinueData = res;
          // this.getQrcode(this.authenticationContinueData);
          let flowId = this.$storage.s_get("addCompany-backfill");
          // 添加公司抬头、回填金额
          this.authenticationContinue = true;
          this.authenticationContinueFaceVisible = true;
          this.current = 3;
          this.steps = stepsEnter;
          this.enterpriseNoEnter = true;
          // 设置流程id，用于之前没有完成回填金额就退出认证或刷新页面
          this.userAuthData = {
            flowId: flowId
          };
        });
      } else {
        // 判断是否是返回继续认证
        this.authenticationContinue = this.$storage.s_get(
          "authenticationContinue"
        );
        getUserAuthstate().then(res => {
          this.authenticationContinueData = res;
          if (this.authenticationContinue) {
            this.authType = "authenticationContinue";
            this.authenticationContinueFaceVisible = true;
            // this.getQrcode(this.authenticationContinueData);
          }
          switch (res.authState) {
            // 未进行认证
            case auth.unverified.value:
              this.current = 0;
              this.steps = steps;
              break;
            // 已完成个人认证
            case auth.person.value:
              this.current = 1;
              this.steps = steps;
              break;
            // 待回填金额
            case auth.backfill.value:
              this.current = 3;
              this.steps = stepsEnter;
              this.enterpriseNoEnter = true;
              // 设置流程id，用于之前没有完成回填金额就退出认证或刷新页面
              this.userAuthData = {
                flowId: res.flowId
              };
              break;
            // 企业认证失败
            case auth.failed.value:
              this.current = 1;
              this.steps = steps;
              break;
            // 等待审核企业认证
            case auth.auditing.value:
              this.current = 5;
              this.steps = stepsEnter;
              this.enterpriseNoEnter = true;
              break;
            // 等待企业审批
            case auth.examining.value:
              this.current = 3;
              this.steps = steps;
              break;
            // 通过认证
            case auth.finish.value:
              this.finish = true;
              break;
            default:
              this.current = 0;
              this.steps = steps;
              break;
          }
          // }
        });
      }
    }
  },
  created() {
    this.init();
  },
  mounted() {
    // 刷新或关闭页面时提示
    window.onbeforeunload = function(e) {
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = "确定重新加载/离开此页面？";
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return "确定重新加载/离开此页面？";
    };
  },
  beforeRouteLeave(to, from, next) {
    if (isLogin()) {
      if (
        this.finish ||
        (!this.enterpriseNoEnter && this.current === 3) ||
        (this.enterpriseNoEnter && this.current === 5)
      ) {
        next();
      } else {
        let content =
          this.enterpriseNoEnter && this.current === 3
            ? "您还未完成认证，若离开当前页面，可点击用户姓名-回填金额按钮返回当前页面，是否确认离开?"
            : "您还未完成认证流程，若强制离开当前页面，后续需重新走认证流程，是否确认离开?";
        this.$confirm({
          title: "温馨提示",
          content: content,
          onOk() {
            next();
          }
        });
      }
    } else {
      next();
    }
  },
  beforeDestroy() {
    // 清除刷新或关闭页面的监听
    window.onbeforeunload = null;
    // 删除继续认证标识
    this.$storage.s_remove("authenticationContinue");
    this.$storage.s_remove("addCompany");
    this.$storage.s_remove("addCompany-backfill");
  }
};
</script>

<style lang="scss" scoped>
.authentication {
  .finish {
    padding-top: 108px;
  }
  .unfinished {
    padding: 48px 32px;
    max-width: 1000px;
    margin: 0 auto;
  }
  .ant-steps {
    margin: 0 auto;
    margin-bottom: 50px;
  }
  ::v-deep .form_wrapper {
    transform: translateX(-90px);
    width: 450px;
    margin: 0 auto;
  }
}
// .modal {
//   position: absolute;
//   top: 0;
//   left: 0;
//   background-color: rgba(0, 0, 0, 0.45);
//   width: -webkit-fill-available;
//   height: 100%;
//   .ant-alert {
//     text-align: start;
//   }
//   .face {
//     background-color: #fff;
//     width: 410px;
//     margin: 0 auto;
//     text-align: center;
//     padding: 30px 20px;
//     margin-top: 70px;
//     .qrcode {
//       margin: 30px 0 10px;
//     }
//     .tip {
//       margin-bottom: 10px;
//     }
//     .authenticationContinueFaceType {
//       margin-top: 20px;
//     }
//   }
// }
</style>
